package com.mall.module.user.service.Impl;

import com.mall.common.exception.BusinessException;
import com.mall.common.result.ResultCode;
import com.mall.module.user.domain.dto.UserAddressDTO;
import com.mall.module.user.domain.entity.UserAddress;
import com.mall.module.user.domain.vo.UserAddressVO;
import com.mall.module.user.mapper.UserAddressMapper;
import com.mall.module.user.service.UserAddressService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
public class UserAddressServiceImpl implements UserAddressService {

    private final UserAddressMapper userAddressMapper;
    
    private static final DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    /**
     * 获取用户地址列表
     *
     * @param userId 用户ID
     * @return 地址列表
     */
    @Override
    public List<UserAddressVO> listUserAddresses(Long userId) {
        List<UserAddress> addresses = userAddressMapper.selectByUserId(userId);
        return addresses.stream()
                .map(this::convertToVO)
                .collect(Collectors.toList());
    }

    /**
     * 获取用户默认地址
     *
     * @param userId 用户ID
     * @return 默认地址
     */
    @Override
    public UserAddressVO getDefaultAddress(Long userId) {
        UserAddress address = userAddressMapper.selectDefaultByUserId(userId);
        return address != null ? convertToVO(address) : null;
    }

    /**
     * 获取地址详情
     *
     * @param addressId 地址ID
     * @return 地址详情
     */
    @Override
    public UserAddressVO getAddressById(Long addressId) {
        UserAddress address = userAddressMapper.selectById(addressId);
        return address != null ? convertToVO(address) : null;
    }

    /**
     * 添加收货地址
     *
     * @param userId 用户ID
     * @param addressDTO 地址信息
     * @return 是否成功
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean addAddress(Long userId, UserAddressDTO addressDTO) {
        UserAddress address = new UserAddress();
        BeanUtils.copyProperties(addressDTO, address);
        address.setUserId(userId);
        address.setCreateTime(LocalDateTime.now());
        
        // 如果是默认地址，先取消其他默认地址
        if (Boolean.TRUE.equals(address.getIsDefault())) {
            userAddressMapper.cancelDefault(userId);
        }
        
        return userAddressMapper.insert(address) > 0;
    }

    /**
     * 修改收货地址
     *
     * @param userId 用户ID
     * @param addressId 地址ID
     * @param addressDTO 地址信息
     * @return 是否成功
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateAddress(Long userId, Long addressId, UserAddressDTO addressDTO) {
        // 检查地址是否存在
        UserAddress existingAddress = userAddressMapper.selectById(addressId);
        if (existingAddress == null) {
            throw new BusinessException(ResultCode.DATA_NOT_EXISTED);
        }
        
        // 检查地址是否属于该用户
        if (!existingAddress.getUserId().equals(userId)) {
            throw new BusinessException(ResultCode.FORBIDDEN);
        }
        
        UserAddress address = new UserAddress();
        BeanUtils.copyProperties(addressDTO, address);
        address.setAddressId(addressId);
        address.setUserId(userId);
        
        // 如果是默认地址，先取消其他默认地址
        if (Boolean.TRUE.equals(address.getIsDefault()) && !Boolean.TRUE.equals(existingAddress.getIsDefault())) {
            userAddressMapper.cancelDefault(userId);
        }
        
        return userAddressMapper.update(address) > 0;
    }

    /**
     * 删除收货地址
     *
     * @param userId 用户ID
     * @param addressId 地址ID
     * @return 是否成功
     */
    @Override
    public boolean deleteAddress(Long userId, Long addressId) {
        // 检查地址是否存在
        UserAddress existingAddress = userAddressMapper.selectById(addressId);
        if (existingAddress == null) {
            throw new BusinessException(ResultCode.DATA_NOT_EXISTED);
        }
        
        // 检查地址是否属于该用户
        if (!existingAddress.getUserId().equals(userId)) {
            throw new BusinessException(ResultCode.FORBIDDEN);
        }
        
        return userAddressMapper.deleteById(addressId) > 0;
    }

    /**
     * 设置默认地址
     *
     * @param userId 用户ID
     * @param addressId 地址ID
     * @return 是否成功
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean setDefaultAddress(Long userId, Long addressId) {
        // 检查地址是否存在
        UserAddress existingAddress = userAddressMapper.selectById(addressId);
        if (existingAddress == null) {
            throw new BusinessException(ResultCode.DATA_NOT_EXISTED);
        }
        
        // 检查地址是否属于该用户
        if (!existingAddress.getUserId().equals(userId)) {
            throw new BusinessException(ResultCode.FORBIDDEN);
        }
        
        // 先取消其他默认地址
        userAddressMapper.cancelDefault(userId);
        
        // 设置新的默认地址
        return userAddressMapper.setDefault(userId, addressId) > 0;
    }
    
    /**
     * 将实体转换为VO
     */
    private UserAddressVO convertToVO(UserAddress address) {
        UserAddressVO vo = new UserAddressVO();
        BeanUtils.copyProperties(address, vo);
        vo.setCreateTime(address.getCreateTime().format(FORMATTER));
        return vo;
    }
} 